package com.yh.yhso.manager;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yh.yhso.common.ErrorCode;
import com.yh.yhso.datasource.*;
import com.yh.yhso.exception.ThrowUtils;
import com.yh.yhso.model.dto.search.SearchRequest;
import com.yh.yhso.model.entity.Picture;
import com.yh.yhso.model.enums.SearchTypeEnum;
import com.yh.yhso.model.vo.PostVO;
import com.yh.yhso.model.vo.SearchVO;
import com.yh.yhso.model.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 搜索门面（门面模式）
 *
 * @author Yh
 */
@Component
public class SearchFacade {


    @Resource
    private PictureDataSource pictureDataSource;

    @Resource
    private PostDataSource postDataSource;

    @Resource
    private UserDataSource userDataSource;

    @Resource
    private DataSourceRegistry dataSourceRegistry;


    public SearchVO searchAll(@RequestBody SearchRequest searchRequest, HttpServletRequest request) throws IOException {
        // 判断请求的类型是否合法
        String type = searchRequest.getType();
        ThrowUtils.throwIf(StringUtils.isBlank(type), ErrorCode.PARAMS_ERROR);
        SearchTypeEnum searchTypeEnum = SearchTypeEnum.getEnumByValue(type);
        String searchText = searchRequest.getSearchText();
        long current = searchRequest.getCurrent();
        long pageSize = searchRequest.getPageSize();
        SearchVO searchVO = new SearchVO();
        // 前端传递的type==null 搜索出所有数据
        if (searchTypeEnum == null) {
            // 图片数据请求
            Page<Picture> picturePage = pictureDataSource.doSearch(searchText, 1, 10);
            // 用户数据请求
            Page<UserVO> userVOPage = userDataSource.doSearch(searchText, current, pageSize);
            // 帖子数据请求
            Page<PostVO> postVOPage = postDataSource.doSearch(searchText, current, pageSize);

            // 将三个list数据转化为VO返回给前端
            searchVO.setUserList(userVOPage.getRecords());
            searchVO.setPostList(postVOPage.getRecords());
            searchVO.setPictureList(picturePage.getRecords());
        }
        // 根据搜索（type）类型请求数据
        else {
            // 根据type获得对应的数据源
            DataSource<?> dataSource = dataSourceRegistry.getDataSourceByType(type);
            Page<?> page = dataSource.doSearch(searchText, current, pageSize);
            searchVO.setDataList(page.getRecords());
        }
        return searchVO;
    }
}


